package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RequestMapping("/member")
@RestController
public class MemberController {
    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    //登录
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");//手机号
        String validateCode = (String) map.get("validateCode");//表单中的验证码
        String s = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);//jedis中的验证码
        if (!validateCode.equals(s) || validateCode == null) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } else {
            //判断用户是否是会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //不是会员,自动注册
                member = new Member();
                member.setPhoneNumber((String) map.get("telephone"));//设置手机号
                member.setRegTime(new Date());//设置注册时间
                memberService.add(member);//添加会员
            }
            //登陆成功
            Cookie login_member_telephone = new Cookie("login_member_telephone", telephone);
            //将手机号存入到cookie中
            response.addCookie(login_member_telephone);
            login_member_telephone.setPath("/");//路径
            //保存会员信息到redis中,reids中只能存java对象
            String redis_member = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 1800, redis_member);//这个方法能设置key，value和时间
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
    }
}
